import { useEffect, useState } from 'react';
import { useAliveController } from 'react-activation';
import { history } from 'umi';
import { useLocation } from 'dva';
import { DEFAULT_ROUTE, OPERATION_TYPE } from '../shared.data';

export function useKeepAliveTabs() {
  const [activeTabRoutePath, setActiveTabRoutePath] = useState(DEFAULT_ROUTE.path);

  const { getCachingNodes, dropScope, refreshScope } = useAliveController();
  const keepAliveTabs = getCachingNodes?.() || [];

  const { pathname: currPath } = useLocation();

  // 页面在非房源登记强刷时 缓存区还没有房源登记页面
  const isReload = !keepAliveTabs.find(item => item.cacheKey === DEFAULT_ROUTE.path);

  const menuItems = [
    {
      label: '刷新',
      key: OPERATION_TYPE.REFRESH,
    },
    keepAliveTabs.length <= 1 && !isReload
      ? null
      : {
          label: '关闭',
          key: OPERATION_TYPE.CLOSE,
        },
    keepAliveTabs.length <= 1 && !isReload
      ? null
      : {
          label: '关闭其他',
          key: OPERATION_TYPE.CLOSEOTHER,
        },
  ].filter(Boolean);

  // 关闭tab
  const closeTab = (targetPath = activeTabRoutePath) => {
    if (currPath === targetPath) {
      const currIdx = keepAliveTabs.findIndex(item => item.name === targetPath);
      const p = keepAliveTabs[currIdx - 1]?.name || DEFAULT_ROUTE.path;
      history.push(p);
      setActiveTabRoutePath(p);
    }
    dropScope(targetPath);
  };

  // 关闭其他
  const closeOtherTab = (routePath = activeTabRoutePath) => {
    const toCloseTabs = keepAliveTabs.filter(
      o => [routePath, DEFAULT_ROUTE.path].includes(o.cacheKey) === false,
    );
    // 如果在其他页面关闭当前页面 需要先跳转到触发关闭的页面
    history.push(routePath);

    toCloseTabs.forEach(tab => {
      dropScope(tab.cacheKey);
    });
  };

  // 刷新tab
  const refreshTab = (routePath = activeTabRoutePath) => {
    refreshScope(routePath);
  };

  // 右键菜单事件
  const menuClick = ({ key, domEvent }) => {
    const { type, cacheKey } = JSON.parse(key);
    domEvent.stopPropagation();
    switch (type) {
      case OPERATION_TYPE.REFRESH:
        refreshTab(cacheKey);
        break;
      case OPERATION_TYPE.CLOSE:
        closeTab(cacheKey);
        break;
      case OPERATION_TYPE.CLOSEOTHER:
        closeOtherTab(cacheKey);
        break;
      default:
        break;
    }
  };

  useEffect(() => {
    setActiveTabRoutePath(currPath);
  }, [keepAliveTabs.length, currPath]);

  return {
    keepAliveTabs,
    activeTabRoutePath,
    currPath,
    menuItems,
    closeTab,
    refreshTab,
    closeOtherTab,
    setActiveTabRoutePath,
    menuClick,
  };
}
